package com.opengw.configuration.support;


import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.opengw.exception.OpenGWException;

public class SSLCertificateCapturer {
	private X509Certificate certificate;
	private String host;
	private int port;

	public SSLCertificateCapturer(String urlString) throws MalformedURLException {
		URL url = new URL(urlString);
		this.host = url.getHost();
		this.port = url.getPort();
		if(this.port == -1)
			this.port = 443;
		
		
	}

	public X509Certificate captureSSLCertificate() throws OpenGWException {
		try{
			SSLContext sc = SSLContext.getInstance("SSL");
			TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
	
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}
	
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] certs, String authType) {
				}
	
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] certs, String authType) {
					//Get SSL certificate
					certificate = certs[0];
				}
			} };
			sc.init(null, trustManager, new java.security.SecureRandom());
			SSLSocketFactory factory = sc.getSocketFactory();
			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
			socket.startHandshake();
		} catch (Exception e) {
		}
		
		if(certificate != null)
			return certificate;
		else
			throw new OpenGWException(OpenGWException.CAN_NOT_GET_SSL_CERTIFICATE);

	}

}
